<template>
  <div class="container">
    <div class="search-main">
      <el-form ref="queryRef" :inline="true" :model="queryParams" label-width="68px">
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="queryParams.menuName" clearable placeholder="请输入菜单名称" style="width: 200px"
                    @keyup.enter="handleQuery"/>
        </el-form-item>

        <el-form-item label="租户状态" prop="iuse">
          <el-select v-model="queryParams.iuse" clearable placeholder="租户状态" style="width: 200px">
            <el-option :key="1" :value="1" label="正常">正常</el-option>
            <el-option :key="0" :value="0" label="停用">停用</el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button icon="Search" size="" type="primary" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" size="" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-row class="">
      <el-col :span="24">
        <el-button icon="Plus" plain size="" type="primary" @click="handleAdd()">新增</el-button>
      </el-col>
    </el-row>

    <!-- 表格-->
    <vxe-grid ref="gridRef" v-bind="gridOptions">

      <template #menuType="{ row }">
        <el-tag v-if="row.menuType == 1" type="primary">目录</el-tag>
        <el-tag v-else-if="row.menuType == 2" type="danger">菜单</el-tag>
        <el-tag v-else type="success">按钮</el-tag>
      </template>

      <template #menuOfSystem="{ row }">
        <el-text>{{ row.menuOfSystem == 1 ? 'PC' : 'APP' }}</el-text>
      </template>
      <template #systemType="{ row }">
        <el-text>{{ row.systemType == 1 ? 'EMS' : '运营端' }}</el-text>
      </template>

      <template #menuIcon="{ row }">
        <svgIcon :name="row.menuIcon"/>
      </template>

      <template #iuse="{ row }">
        <el-tag :type="row.iuse ? 'primary' : 'danger'">{{ row.iuse ? '正常' : '停用' }}</el-tag>
      </template>

      <template #action="{ row }">
        <el-button plain size="" type="primary" @click="editRowEvent(row)">编辑</el-button>
        <el-popconfirm title="确实要删除当前项吗?" @confirm="deleteRow(row)">
          <template #reference>
            <el-button color="#ff4444f7" plain size="" type="primary" @click="">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </vxe-grid>

    <!-- 添加或修改对话框 -->
    <el-dialog v-model="state.dialogVisible" :before-close="handleDialogBeforeClose" :close-on-click-modal="false"
               :closed="cancel" :destroy-on-close="false" append-to-body class="dialog-custom"
               title="新增菜单"
               width="680">
      <el-form ref="menuRef" :model="form" :rules="rules" label-width="100">
        <el-row>
          <el-col :span="24">
            <el-form-item class="dislog-label-item" label="上级菜单" prop="parentId">
              <el-tree-select v-model="form.parentId"
                              :data="menuOptions" :props="{ value: 'id', label: 'menuName', children: 'children' }"
                              check-strictly placeholder="选择上级菜单" value-key="menuId"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item class="dislog-label-item" label="菜单类型" prop="menuType">
              <el-radio-group v-model="form.menuType">
                <el-radio :value="1">目录</el-radio>
                <el-radio :value="2">菜单</el-radio>
                <el-radio :value="3">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType != '3'" :span="12">
            <el-form-item class="dislog-label-item" label="菜单图标" prop="menuIcon">
              <el-popover :width="540" placement="bottom-start" trigger="click">
                <template #reference>
                  <el-input v-model="form.menuIcon" placeholder="点击选择图标" readonly @blur="showSelectIcon">
                    <template #prefix>
                      <svgIcon v-if="form.menuIcon" :name="form.menuIcon"
                               class="el-input__icon" style="height: 32px;width: 16px;"/>
                      <el-icon v-else style="height: 32px;width: 16px;">
                        <search/>
                      </el-icon>
                    </template>
                  </el-input>
                </template>
                <IconSelect ref="iconSelectRef" :active-icon="form.icon" @selected="selected"/>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType != '3'" :span="12">
            <el-form-item class="dislog-label-item" label="显示排序" prop="menuSort">
              <el-input-number v-model="form.menuSort" :min="0" controls-position="right"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="dislog-label-item" label="菜单名称" prop="menuName">
              <el-input v-model="form.menuName" placeholder="请输入菜单名称"/>
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType != '3'" :span="12">
            <el-form-item class="dislog-label-item" label="路由地址" prop="menuPath">
              <el-input v-model="form.menuPath" placeholder="请输入路由地址"/>
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType != '3'" :span="12">
            <el-form-item class="dislog-label-item" label="路由名称" prop="menuModuleName">
              <el-input v-model="form.menuModuleName" placeholder="请输入路由名称"/>
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType == '2'" :span="12">
            <el-form-item class="dislog-label-item" label="组件路径" prop="menuModuleLocation">
              <el-input v-model="form.menuModuleLocation" placeholder="请输入组件路径"/>
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType == '1'" :span="12">
            <el-form-item class="dislog-label-item" label="重定向" prop="redirect">
              <el-input v-model="form.redirect" placeholder="请输入路由重定向地址"/>
            </el-form-item>
          </el-col>


          <el-col v-if="form.menuType == '3'" :span="12">
            <el-form-item class="dislog-label-item" label="权限字符" prop="authCode">
              <el-input v-model="form.authCode" placeholder="请输入权限标识"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item class="dislog-label-item" label="所属系统">
              <el-select v-model="form.systemType" placeholder="请输入所属系统">
                <el-option :value="1" label="EMS"/>
                <el-option :value="2" label="EMS配置端"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="dislog-label-item" label="所属终端">
              <el-select v-model="form.menuOfSystem" placeholder="请输入所属终端">
                <el-option :value="1" label="PC"/>
                <el-option :value="2" label="APP"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-row>
              <el-col v-if="form.menuType != '3'" :span="12">
                <el-form-item class="dislog-label-item">
                  <template #label>
                                        <span>
                                            <el-tooltip content="选择是外链则路由地址需要以`http(s)://`开头"
                                                        placement="top">
                                                <el-icon><question-filled/></el-icon>
                                            </el-tooltip>是否外链
                                        </span>
                  </template>
                  <el-radio-group v-model="form.isFrame">
                    <el-radio :value="1">是</el-radio>
                    <el-radio :value="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col v-if="form.menuType != '3'" :span="12">
                <el-form-item class="dislog-label-item" label="外链地址" prop="frameUrl">
                  <el-input v-model="form.frameUrl" placeholder="请输入外链地址"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>

          <el-col v-if="form.menuType == '2'" :span="12">
            <el-form-item class="dislog-label-item" label="是否缓存">
              <el-radio-group v-model="form.cache">
                <el-radio :value="1">缓存</el-radio>
                <el-radio :value="0">不缓存</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType != '3'" :span="12">
            <el-form-item class="dislog-label-item" label="显示状态">
              <el-radio-group v-model="form.menuShow">
                <el-radio :value="0">隐藏</el-radio>
                <el-radio :value="1">显示</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="dislog-label-item" label="菜单状态">
              <el-radio-group v-model="form.iuse">
                <el-radio :value="0">停用</el-radio>
                <el-radio :value="1">使用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(menuRef)">确 定</el-button>
          <el-button @click="cancel(menuRef)">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script name="SystemMenu" setup>
import {defineAsyncComponent, getCurrentInstance, onMounted, reactive, ref, toRefs} from "vue";
import * as SystemApi from "@/api/systemApi";
import {ElMessage} from "element-plus";
import {DEFAULT_ID} from '@/utils/constants';

const IconSelect = defineAsyncComponent(() => import('@/components/iconSelect/index.vue'));

const {proxy} = getCurrentInstance();
const menuOptions = ref([]);
const iconSelectRef = ref(null);
const gridRef = ref();
const queryRef = ref(null);
const menuRef = ref();
const {log} = console;


//组件状态
const state = reactive({
  dialogVisible: false,
  form: {
    menuType: 1,
    parentId: '',
    menuSort: 1,
    isFrame: 0,
    menuPath: '',
    authCode: '',
    menuShow: 1,
    cache: 1,
    iuse: 1,
    menuIcon: '',
    systemType: 2,
    frameUrl: '',
    menuOfSystem: 1,
    menuModuleName: '',
    menuModuleLocation: '',
  },
  queryParams: {
    menuName: null,
    iuse: null,
  },
  rules: {
    menuName: [{required: true, message: "菜单名称不能为空", trigger: "blur"}],
    parentId: [{required: true, message: "上级菜单不能为空", trigger: "change"}],
    path: [{required: true, message: "路由地址不能为空", trigger: "blur"}]
  },
});

const {queryParams, form, rules} = toRefs(state);

/** 查询菜单下拉树结构 */
async function getTreeselect() {
  menuOptions.value = [];
  const res = await SystemApi.treeMenu();
  const menu = {id: DEFAULT_ID, menuName: "主类目", children: []};

  if (res.code == 200 && res.data.length > 0) {
    menu.children = res.data
  }
  menuOptions.value.push(menu);
}

/** 选择图标 */
function selected(name) {
  form.value.menuIcon = name;
}

/** 展示下拉图标 */
function showSelectIcon() {
  iconSelectRef.value.reset();
}

/** 表单重置 */
function reset(formEl) {
  if (!formEl) return;
  formEl.resetFields()
}

//add
async function submitForm(formEl) {
  console.log(formEl, menuRef);
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let res = await SystemApi.menuSave(form.value);
      if (res.code == 200 && res.data) {
        ElMessage.success("操作成功");
        handleQuery();
      }
      cancel(formEl);
    }

  })
}

function cancel(formEl) {
  state.dialogVisible = false;
  reset(formEl);
}

function handleDialogBeforeClose(done) {
  reset(menuRef.value);
  done()
}

//表格配置
const gridOptions = reactive({
  minHeight: 0,
  emptyText: "暂无数据！",
  keepSource: true,
  headerRowClassName: "table-head-cla",
  border: true,
  stripe: false,
  showOverflow: true,
  loading: false,
  align: "left",
  headerAlign: 'center',
  rowConfig: {
    isCurrent: true,
    isHover: true,
    keyField: 'id'
  },
  size: "small",
  autoResize: true,
  columnConfig: {
    isHover: true,
    resizable: true
  },
  treeConfig: {
    expandAll: true,
    rowField: 'id',
    childrenField: 'children',
    trigger: 'default',
    reserve: true
  },
  columns: [
    {field: 'menuName', title: '菜单名称', treeNode: true},
    {field: 'menuIcon', title: '图标', width: 80, slots: {default: 'menuIcon'}, align: 'center'},
    {field: 'menuPath', title: '路由地址', align: 'center'},
    {field: 'menuModuleLocation', title: '组件路径', align: 'center'},
    {field: 'authCode', title: '权限标识', align: 'center'},
    {field: 'systemType', title: '所属系统', slots: {default: 'systemType'}, align: 'center', width: 80},
    {field: 'menuOfSystem', title: '所属终端', slots: {default: 'menuOfSystem'}, align: 'center', width: 80},
    {field: 'menuType', title: '菜单类型', slots: {default: 'menuType'}, align: 'center', width: 80},
    {field: 'iuse', title: '状态', slots: {default: 'iuse'}, align: 'center', width: 80},
    {field: 'menuSort', title: '排序', align: 'center', width: 80},
    {title: "操作", slots: {default: "action"}, align: 'center'},
  ],
  data: []
});

function handleAdd() {
  state.dialogVisible = true;
  form.value.parentId = DEFAULT_ID;
}

//查询list
async function handleQuery() {
  gridOptions.loading = true;
  let res = await SystemApi.menuSearch(queryParams.value);
  if (res.data.length > 0) {
    gridOptions.data = res.data;
  } else {
    gridOptions.data = [];
  }
  gridOptions.loading = false;
  getTreeselect();
}

function resetQuery() {
  queryRef.value.resetFields();
  handleQuery();
}

const editRowEvent = (row) => {
  state.dialogVisible = true;
  form.value = {...row};
};

//删除数据
async function deleteRow(row) {
  let res = await SystemApi.menuDel(row.id);
  if (res.code == 200 && res.data) {
    ElMessage.success("操作成功");
    handleQuery();
  }
}

onMounted(() => {
  handleQuery();
});

</script>

<style lang="scss" scoped>
.el-dialog__body {
  padding: 30px 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}

.container {
  .search-main {
    line-height: 78px;

    .el-form-item {
      margin-bottom: 0px;
    }

    .el-form-item__label {
    }
  }

  .el-row {
    margin-bottom: 10px;
  }
}
</style>
